package server;

import entry.MemberSocket;
import entry.Room;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        ExecutorService executorService = null;
        try{
            serverSocket = new ServerSocket(8808);
        } catch (Exception e){
            System.err.println("Could not listen on port: 8808.");
            System.exit(-1);
        }
        executorService = Executors.newFixedThreadPool(10);
        RoomManager roomManager = RoomManager.getRoomManager();

        while (true){
            try{
                Socket client = serverSocket.accept();
                MemberSocket memberSocket = new MemberSocket(client);
                executorService.submit(memberSocket);
                if (roomManager.hasRoom(memberSocket)==false){
                    Room room = roomManager.add(memberSocket);
                    room.addMember(memberSocket);
                }
                else {
                    Room room = roomManager.getRoom(memberSocket.getMember().getID());
                    room.addMember(memberSocket);
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
